#!/bin/sh -eu

kflavour=
kflavour="${GLOBAL_KFLAVOURS%% *}"

mkdir -p /boot/efi

cp /usr/share/raspberrypi-firmware/*.{bin,dat,elf} /boot/efi/

[ -f /usr/share/u-boot/rpi_3/kernel8.img ] &&
	cp /usr/share/u-boot/rpi_3/kernel8.img \
	   /boot/efi/uboot-rpi_3.bin
[ -f /usr/share/u-boot/rpi_3_32b/kernel7.img ] &&
	cp /usr/share/u-boot/rpi_3_32b/kernel7.img \
	   /boot/efi/uboot-rpi_3_32b.bin
[ -f /usr/share/u-boot/rpi_4/kernel8.img ] &&
	cp /usr/share/u-boot/rpi_4/kernel8.img \
	   /boot/efi/uboot-rpi_4.bin
[ -f /usr/share/u-boot/rpi_4_32b/kernel7.img ] &&
	cp /usr/share/u-boot/rpi_4_32b/kernel7.img \
	   /boot/efi/uboot-rpi_4_32b.bin

# copy actualy dtb's for default kernel
if [ -d /boot/dtb/broadcom ]; then
	DTB_DIR=/boot/dtb/broadcom
elif [ -d /boot/dtb ]; then
	DTB_DIR=/boot/dtb
else
	echo "Error: /boot/dtb/broadcom or /boot/dtb is not exists!!!" >&2
	exit 1
fi

cp "$DTB_DIR"/bcm27*-rpi-*.dtb /boot/efi/ || :

[ -f /boot/efi/bcm2710-rpi-3-b.dtb ] ||
	cp "$DTB_DIR"/bcm2837-rpi-3-b.dtb \
	   /boot/efi/bcm2710-rpi-3-b.dtb || :
[ -f /boot/efi/bcm2710-rpi-3-b-plus.dtb ] ||
	cp "$DTB_DIR"/bcm2837-rpi-3-b-plus.dtb \
	   /boot/efi/bcm2710-rpi-3-b-plus.dtb || :
[ -f /boot/efi/bcm2710-rpi-cm3.dtb ] ||
	cp "$DTB_DIR"/bcm2837-rpi-cm3-io3.dtb \
	   /boot/efi/bcm2710-rpi-cm3.dtb || :
[ -f /boot/efi/bcm2711-rpi-cm4.dtb ] ||
	cp "$DTB_DIR"/bcm2711-rpi-cm4-io.dtb \
	   /boot/efi/bcm2711-rpi-cm4.dtb || :
[ -d /boot/dtb/overlays ] &&
	cp -r /boot/dtb/overlays /boot/efi/ || :

# copy missing dtb's from raspberrypi-firmware
for dtb in /usr/share/raspberrypi-firmware/*.dtb; do
	[ -f "/boot/efi/$(basename $dtb)" ] ||
		cp "$dtb" /boot/efi/
done

[ "$GLOBAL_ARCH" = aarch64 ] && \
	echo "arm_64bit=1" > /boot/efi/config.txt

cat >> /boot/efi/config.txt <<EOF
enable_uart=1
disable_overscan=1
dtparam=audio=on
hdmi_ignore_edid_audio=1

[pi3]
kernel=uboot-rpi_3.bin
#dtoverlay=vc4-fkms-v3d

[pi4]
kernel=uboot-rpi_4.bin
#dtoverlay=vc4-fkms-v3d
#max_framebuffers=2

[all]
EOF

[ "$GLOBAL_ARCH" = armh ] && \
	sed -i 's/.bin/_32b.bin/g' /boot/efi/config.txt

# Enable bootloading without u-boot
if [ -n "${GLOBAL_RPI_NOUBOOT-}" ]; then
	rpi4-boot-nouboot $kflavour
	sed -i '/#dtoverlay=vc4-fkms-v3d/s/#//' /boot/efi/config.txt
fi

exit 0
